package com.lyxmaster.lib.bluetooth;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.lyxmaster.lib.util.LogEx;
import com.lyxmaster.lib.util.DataConfig;

/**
 * Created by LYX on 2018/3/22.
 */

public class BtService extends Service {
    public static String ACTION_BLUTOOTHRECVDATA = "app.lyxmaster.com.bluetooth.ACTION_BLUTOOTHRECVDATA";
    public static String BLUETOOTHCONNECT = "app.lyxmaster.com.bluetooth.BLUETOOTHCONNECT";
    public static String EXTRA_BLUTOOTHRECVDATA = "app.lyxmaster.com.bluetooth.EXTRA_BLUTOOTHRECVDATA";

    private Timer timerBtRecv = new Timer();  //蓝牙接收数据超时时间
    private TimerTask timerTaskBtRecv;  //蓝牙接收数据超时时间执行任务
    private List<Byte> recvArray = new ArrayList<>();

    //服务创建
    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    // 服务启动
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    //服务销毁
    @Override
    public void onDestroy() {
        destroy();
        stopSelf(); //自杀服务
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    // IBinder是远程对象的基本接口，是为高性能而设计的轻量级远程调用机制的核心部分。但它不仅用于远程
    // 调用，也用于进程内调用。这个接口定义了与远程对象交互的协议。
    // 不要直接实现这个接口，而应该从Binder派生。
    // Binder类已实现了IBinder接口
    public class MyBinder extends Binder {
        /** * 获取Service的方法 * @return 返回PlayerService */
        public BtService getService(){
            return BtService.this;
        }
    }

    private void init(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);   //开始搜索
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);   //搜索结束
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);    //状态变化
        filter.addAction(BluetoothDevice.ACTION_FOUND); //发现设备
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); //设备连接
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);  //设备断开
        filter.addAction(BLUETOOTHCONNECT); //蓝牙连接
        this.registerReceiver(myReceiver, filter);
    }

    private void resetTimer(){
        if(timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        timerTaskBtRecv = new TimerTask() {
            @Override
            public void run() {
                byte[] data = new byte[recvArray.size()];
                for (int i=0; i<data.length; i++){
                    data[i] = recvArray.get(i);
                }
                Intent broadCastIntent = new Intent();
                broadCastIntent.setAction(ACTION_BLUTOOTHRECVDATA);
                broadCastIntent.putExtra(EXTRA_BLUTOOTHRECVDATA, data);
                sendBroadcast(broadCastIntent);
                recvArray.clear();
                LogEx.Log(DataConfig.hexByteToHexString(data));
            }
        };
        timerBtRecv.schedule(timerTaskBtRecv,300);
    }

    private void destroy(){
        this.unregisterReceiver(myReceiver);
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(BLUETOOTHCONNECT.equals(intent.getAction())){    //蓝牙已连接
                onBtRecv();
            }
        }
    };

    private void onBtRecv(){
        new Thread(){
            public void run(){
                try{
                    while (true){
                        byte[] data = new byte[1024];
                        int length = BtHelper.getInstance().btIs.read(data);

                        for(int i=0; i<length; i++){
                            recvArray.add(data[i]);
                        }
                        resetTimer();
                    }
                }catch (Exception e){
                    resetTimer();
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
